# -*- coding: utf-8 -*-

'''eof
name:申请企业未结清借贷业务担保方式余额占比分布
code:EC65_EntUnsettledGuarantyDistribution
tableName:
columnName:
groups:行内二代企业征信数据
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

from dateutil.parser import parse
import json
def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
    获取表信息
    :param data:表上层的字典对象
    :param tableName:表的名字
    :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
    :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
    :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

#计算分母值;
def EntUnsettledGuarantyDistribution_denominator():
    data = EC_DSJ_2D.get('data')
    #信用提示信息,出现次数[1..1],下级字段出现次数[1..1]
    EBA = getTable(data, 'EBA', 1, 1)
    if EBA == [{}]:
        return u'缺失值'
    elif EBA == 0:
        return 0
    else:
        #信用提示信息单元,出现次数[1..1]，下级字段出现次数[0..1]
        EB01 = getTable(EBA[0], 'EB01', 1, 0)
        if EB01 == [{}]:
            return u"缺失值"
        elif EB01 == 0:
            return 0
        else:
            #信贷交易提示信息段,出现次数[0..1]，下级字段出现次数[1..1]
            EB01A = getTable(EB01[0], 'EB01A', 0, 1)
            if EB01A == [{}]:
                return u"缺失值"
            elif EB01A == 0:
                return 0
            else:
                #信贷交易提示信息段，出现次数[1..1]，下级字段出现次数[1..1]
                EB01AJ01 = EB01A[0].get('EB01AJ01')
                if isfloat(EB01AJ01):
                    return float(EB01AJ01)  #总额
                else:
                    return u"缺失值"


#获取分母字典         
def EntUnsettledGuarantyDistribution_numerato():
    guarantyType =  ['0-信用/免担保','1-保证','2-质押','3-抵押','4-组合']
    Dict_bal = {}
    for i in guarantyType:
        Dict_bal.update({i:u'缺失值'})
    Dict_bal_0 = {}
    for i in guarantyType:
        Dict_bal_0.update({i:0})
    data = EC_DSJ_2D.get('data')
    #借贷账户信息,出现次数[1..1]，下级字段出现次数[0..*]
    EDA = getTable(data, 'EDA', 1, 0)
    if EDA == [{}]:
        return Dict_bal
    elif EDA == 0:
        return Dict_bal_0
    else:
        #借贷账户信息单元,出现次数[0..*]，下级字段出现次数[1..1]
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        if ED01 == [{}]:
            return Dict_bal
        elif ED01 == 0:
            return Dict_bal_0
        else:
            conts = 0
            bal_0 = [0]    #担保方式为0-信用/免担保的总余额
            bal_1 = [0]    #担保方式为1-保证的总余额
            bal_2 = [0]    #担保方式为2-质押的总余额
            bal_3 = [0]    #担保方式为3-抵押的总余额
            bal_4 = [0]    #担保方式为4-组合的总余额
            for i in ED01:
                try:
                    #基本信息段,出现次数[1..1]，下级字段出现次数[1..1]
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    #还款表现信息段,出现次数[1..1]，下级字段出现次数[1..1] 
                    ED01B = getTable(i, 'ED01B', 1, 1)
                    if ED01A == [{}] or ED01B == [{}]:
                        conts += 1
                    elif ED01A == 0 or ED01B == 0:
                        pass
                    else:
                        #账户活动状态
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        #担保方式
                        ED01AD08 = ED01A[0].get('ED01AD08')
                        #还款信息，出现次数[0..*]，下级字段出现次数[1..1]
                        ED01BH = getTable(ED01B[0],'ED01BH', 1, 1)
                        if ED01BH == [{}]:
                            conts += 1
                            continue
                        elif ED01BH == 0:
                            pass
                        else:
                            ED01BHConts = 0
                            ED01BHDict = {}
                            for i in ED01BH: #由于ED01BH是列表，没有办法直接取余额，所以根据最大的余额变化日期取对应余额
                                #余额
                                ED01BJ01_tem = i.get("ED01BJ01")
                                #余额变化日期
                                ED01BR02_tem = i.get("ED01BR02")
                                if not parse(ED01BR02_tem) or not isfloat(ED01BJ01_tem):
                                    ED01BHConts += 1
                                else:
                                    ED01BHDict.update({parse(ED01BR02_tem):float(ED01BJ01_tem)})
                            if ED01BHConts == len(ED01BH):
                                conts += 1
                            else:
                                ED01BJ01 = ED01BHDict[max(list(ED01BHDict.keys()))]
                            if ED01AD01 in null_type_list or ED01AD08 in null_type_list or ED01BJ01 in null_type_list\
                            or not isfloat(ED01AD01) or not isfloat(ED01AD08) or not isfloat(ED01BJ01):
                                conts += 1
                            else:
                                if ED01AD01 in [1,'1'] and ED01AD08 in [0,"0"]:
                                    bal_0.append(float(ED01BJ01))
                                elif ED01AD01 in [1,'1'] and ED01AD08 in [1,"1"]:
                                    bal_1.append(float(ED01BJ01))
                                elif ED01AD01 in [1,'1'] and ED01AD08 in [2,"2"]:
                                    bal_2.append(float(ED01BJ01))
                                elif ED01AD01 in [1,'1'] and ED01AD08 in [3,"3"]:
                                    bal_3.append(float(ED01BJ01))
                                elif ED01AD01 in [1,'1'] and ED01AD08 in [4,"4"]:
                                    bal_4.append(float(ED01BJ01))
                                else:
                                    pass
                except:
                    conts += 1
            if conts == len(ED01):
                return Dict_bal
            else:
                valueList = [sum(bal_0),sum(bal_1),sum(bal_2),sum(bal_3),sum(bal_4)]
                keyList = list(Dict_bal.keys())
                for i in range(len(valueList)):
                    Dict_bal.update({keyList[i]:valueList[i]})
                return Dict_bal
            
            
def EC65_EntUnsettledGuarantyDistribution():
    TotalBalance  = EntUnsettledGuarantyDistribution_denominator()
    Dict_bal = EntUnsettledGuarantyDistribution_numerato()
    Dict_bal_ratio = {}
    for i in list(Dict_bal.keys()):
        if TotalBalance == 0:
            if Dict_bal[i] == 0:
                ratio_tem = 0
                Dict_bal_ratio.update({i:ratio_tem})
            else:
                ratio_tem = u'缺失值'
                Dict_bal_ratio.update({i:ratio_tem})
        elif TotalBalance == u'缺失值':
            ratio_tem = u'缺失值'
            Dict_bal_ratio.update({i:ratio_tem})
        else:
            if Dict_bal[i] == u'缺失值':
                ratio_tem = 0
                Dict_bal_ratio.update({i:ratio_tem})
            else:
                ratio_tem = round(Dict_bal[i]/TotalBalance,4)
                Dict_bal_ratio.update({i:ratio_tem})
    return json.dumps({'Dict_bal': Dict_bal, 'Dict_bal_ratio': Dict_bal_ratio}, ensure_ascii=False)
                        
                
result = EC65_EntUnsettledGuarantyDistribution()
